import axios from 'axios'
import {
  Message
} from 'element-ui'
import store from '@/store'
import Qs from 'qs' // 处理post请求数据格式
import {
  getToken,
  removeToken
} from '@/utils/auth'
import VueRouter from 'vue-router'
// axios.defaults.crossDomain = true
// Vue.prototype.$http = axios // 这里并发请求以便在组件使用this.$http.all()，具体看dashborad页面
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // config.headers['Content-Type'] = 'application/json; charset=utf-8'
    // config.ContentType = 'application/json; charset=utf-8'
    // if (config.method === 'post') {
    // config.data = Qs.stringify({
    // ...config.data
    // })
    // console.log(config)
    // if (config.headers['Content-Type'] === 'multipart/form-data; charset=UTF-8') {
    // config.data = config.data ? config.data : Qs.stringify({
    //   ...config.data
    // })
    // }
    // console.log(config.data)
    // for (var key in config.data) {
    //   console.log(key + '---' + config.data[key], Object.prototype.toString.call(config.data[key]))
    //   if (Object.prototype.toString.call(config.data[key]) === '[object Object]') {
    //     // 对象
    //     config.headers[key] = encodeURI(JSON.stringify(config.data[key]))
    //   } else {
    //     // 非对象
    //     config.headers[key] = encodeURI(config.data[key])
    //   }
    // }
    // console.log('JSON.stringify:', JSON.stringify(config.data))
    // config.headers['Client-Params'] = encodeURIComponent(JSON.stringify(config.data))
    // config.data = null
    // console.log('config:', config)
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    // }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  function (error) {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // const res = response.data
    // console.log(response)
    // if the custom code is not 20000, it is judged as an error.
    // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    // to re-login
    //   MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //     confirmButtonText: 'Re-Login',
    //     cancelButtonText: 'Cancel',
    //     type: 'warning'
    //   }).then(() => {
    //     store.dispatch('user/resetToken').then(() => {
    //       location.reload()
    //     })
    //   })
    // }
    // console.log(JSON.stringify(response.data))// for debug
    // return Promise.reject(new Error(res.message || 'Error'))
    return response.data
  },
  error => {
    console.log(JSON.stringify(error.response.data))// for debug
    if (error.response.data.code === -2) {
      // 删除登录态
      console.log('删除登录态')
      removeToken()
      Message({
        message: error.response.data.msg,
        type: 'error',
        duration: 5 * 1000
      })
      VueRouter.push({
        path: '/login'
      })
    } else {
      // 正常错误
      Message({
        message: error.response.data.msg,
        type: 'error',
        duration: 5 * 1000
      })
    }

    return Promise.reject(error)
  }
)
export default service
